import { useEffect, useState, useCallback } from 'react';
import clsx from 'clsx';
import Heading from '@theme/Heading';
import ShowcaseCard from '../ShowcaseCard';
import { getLoginMessage } from '@site/src/constants/index';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import { useLocation } from '@docusaurus/router';
import { type TagType } from '@site/src/data/tags';
import { gotoLogin } from '@site/src/utils/auth';

import styles from './styles.module.css';

// 类型定义
interface Community {
  communityId: string;
  communityName: string;
  url: string;
  pic: string;
  profile: string;
  labelsArray: TagType[];
  focus: boolean;
  communityCode: string;
  showFocusButton: boolean;
}

type Communities = Community[];

// API 配置
const API_CONFIG = {
  PAGE_SIZE: 999,
  PAGE_NUM: 1,
} as const;

export default function ShowcaseCards() {
  const [communities, setCommunities] = useState<Communities>([]);
  const [loading, setLoading] = useState(true);
  const [processedCommunityCodes, setProcessedCommunityCodes] = useState<Set<string>>(new Set());
  const {
    siteConfig: {customFields},
  } = useDocusaurusContext();

  const location = useLocation();
  const apiUrl = customFields.apiUrl as string;

const clearCommunityCodeParam = useCallback(() => {
  if (typeof window === 'undefined') {
    return;
  }

  const url = new URL(window.location.href);

  url.searchParams.delete('CommunityCode');
  window.history.replaceState({}, '', url.toString());
}, []);

const fetchCommunities = useCallback(async () => {
  try {
    const response = await fetch(`${apiUrl}/api/pop_open/v1/page/communities`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'token': getLoginMessage() || '',
      },
      body: JSON.stringify({
        pageNum: API_CONFIG.PAGE_NUM,
        pageSize: API_CONFIG.PAGE_SIZE,
        keywords: '',
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    setCommunities(data?.records || []);
  }
  catch (error) {
    console.error('获取社区数据时出错:', error);
    setCommunities([]);
  }
  finally {
    setLoading(false);
  }
}, [apiUrl]);

const handleCommunityJoin = useCallback(async (communityCode: string) => {
  const userLogin = getLoginMessage();

  if (!userLogin) {
    gotoLogin(communityCode);
    return false;
  }

  try {
    const response = await fetch(`${apiUrl}/api/pop_open/v1/community/user/join/communities`, {
      method: 'POST',
      headers: {
        'token': userLogin,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        communityCodes: [communityCode],
      }),
    });

    if (!response.ok) {
      if (response.status === 401) {
        gotoLogin(communityCode);
        return false;
      }

      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData?.message || '关注社区失败，请稍后重试');
    }
  }
  catch (error) {
    throw error;
  }

  return true;
}, [apiUrl]);

  const handleJoinSuccess = useCallback(() => {
    fetchCommunities();
  }, [fetchCommunities]);

  useEffect(() => {
    fetchCommunities();
  }, [fetchCommunities]);

  useEffect(() => {
    if (loading) {
      return;
    }

    const params = new URLSearchParams(location.search);
    const communityCode = params.get('CommunityCode');

    if (!communityCode || communityCode === '/') {
      return;
    }

    const communityExists = communities.some(community => community.communityCode === communityCode);

    const processAutoJoin = async () => {
      // 检查是否已经处理过这个社区代码，避免重复处理
      if (processedCommunityCodes.has(communityCode)) {
        clearCommunityCodeParam();
        return;
      }

      if (communityExists) {
        try {
          const success = await handleCommunityJoin(communityCode);
          if (success) {
            // 成功加入社区后调用成功回调，刷新社区列表确保按钮状态正确
            handleJoinSuccess();
          }
          // 标记为已处理，避免重复执行
          setProcessedCommunityCodes(prev => new Set(prev).add(communityCode));
          clearCommunityCodeParam();
        }
        catch (error) {
          console.error('自动加入社区失败:', error);
          // 即使失败也标记为已处理，避免无限重试
          setProcessedCommunityCodes(prev => new Set(prev).add(communityCode));
          clearCommunityCodeParam();
        }
      }
      else {
        console.warn(`社区代码 ${communityCode} 不存在`);
        // 社区不存在也要标记为已处理，避免重复处理
        setProcessedCommunityCodes(prev => new Set(prev).add(communityCode));
        clearCommunityCodeParam();
      }
    };

    processAutoJoin();
  }, [
    location.search,
    loading,
    communities,
    processedCommunityCodes,
    handleCommunityJoin,
    clearCommunityCodeParam,
    handleJoinSuccess,
  ]);

  if (loading) {
    return (
      <section className="margin-top--lg margin-bottom--xl">
        <div className="container padding-vert--md text--center">
          加载中...
        </div>
      </section>
    );
  }

  if (communities.length === 0) {
    return (
      <section className="margin-top--lg margin-bottom--xl">
        <div className="container padding-vert--md text--center">
          <Heading as="h2">暂无数据</Heading>
        </div>
      </section>
    );
  }

  return (
    <section className="margin-top--lg margin-bottom--xl">
      <div className="container">
        <ul className={clsx('clean-list', styles.cardList)}>
          {communities.map((community) => (
            <ShowcaseCard
              key={community.communityId}
              item={community}
              onCommunityJoin={handleCommunityJoin}
              onJoinSuccess={handleJoinSuccess}
            />
          ))}
        </ul>
      </div>
    </section>
  );
}
